package auth

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/text/gstr"
	"learn-goframe/internal/consts"
	"learn-goframe/internal/model"
	m "learn-goframe/internal/model/request"
	"learn-goframe/internal/service"
	"learn-goframe/utility/response"
	"strings"
)

type sAuth struct {
}

func newAuth() *sAuth {
	return &sAuth{}
}

func init() {
	service.RegisterAuth(newAuth())
}

func (s *sAuth) Ctx(r *ghttp.Request) {
	var tokenString = strings.Replace(r.Request.Header.Get("Authorization"), "Bearer ", "", 1)

	if tokenString == "" {
		response.JsonExit(r, 401, "token error, token is empty")
	}

	// 初始化，务必最开始执行
	customCtx := &model.Context{
		Data: make(g.Map),
		User: &model.ContextUser{
			Token: tokenString,
		},
	}

	service.BizCtx().Init(r, customCtx)

	profileRes, err := service.Request().SendSSORequest(r.Context(), m.Params{
		Method: "GET",
		URL:    fmt.Sprintf("/account/profile"),
	})

	if err != nil {
		response.JsonExit(r, 401, err.Error())
	}

	gitCloudTag := string(consts.GitCloudNormal)
	if gstr.SearchArray(profileRes.Get("Data.tag").Strings(), "1") > -1 {
		gitCloudTag = string(consts.GitCloudPlus)
	}

	customCtx.User = &model.ContextUser{
		Id:          profileRes.Get("Data.id").String(),
		NickName:    profileRes.Get("Data.nickName").String(),
		Account:     profileRes.Get("Data.account").String(),
		Token:       tokenString,
		GitCloudTag: gitCloudTag,
	}

	// 执行下一步请求逻辑
	r.Middleware.Next()
}

func (s *sAuth) CtxAdmin(r *ghttp.Request) {
	if service.BizCtx().Get(r.Context()).User.Account != "admin" {
		response.JsonExit(r, 401, "权限不足，非管理员账号")
	}

	// 执行下一步请求逻辑
	r.Middleware.Next()
}
